package com.squirrels.server.work;

import com.squirrels.server.annotation.NettyServerWorker;
import com.squirrels.server.common.constant.SystemConstant;
import com.squirrels.server.common.constant.UserConstant;
import com.squirrels.server.message.Login;
import com.squirrels.server.message.protobuf.Message;
import com.squirrels.server.service.UserService;
import com.squirrels.server.utils.EntityUtils;
import com.squirrels.server.utils.JWTUtils;
import dev.morphia.Datastore;
import io.netty.channel.socket.DatagramPacket;

/**
 * 创建者: FlyingSquirrels
 * 创建时间: 2024/8/19 11:32
 * 描述: 用户管理Worker
 */

@NettyServerWorker("user")
public class UserWorker extends ServerWorker{

    private static UserService userService;

    /**
     * 为当前类注入service
     * @param datastore
     */
    private void doService(Datastore datastore) {
        userService = UserService.operation(datastore);
    }

    @Override
    public Message.Entity doWorker(String operationBase) {
        // 注入 Service
        doService(datastore);
        Message.Entity responseData;
        // 根据请求头部执行操作
        switch (operationBase){
            // 重新登录获取账号验证信息
            case "relogin" -> {
                responseData = relogin(entity);
            }
            default -> {
                responseData = errorMsg(UserConstant.OPERATION_NOT_ERROR,entity);
            }
        }
        return responseData;
    }

    /**
     * 重新登录
     * @param entity
     * @return
     */
    private Message.Entity relogin(Message.Entity entity) {
        Login login = Login.fromEntity(entity);
        if (!Login.accountIsNotNull(login)) {
            return errorMsg(UserConstant.ACCOUNT_EXCEPTION,entity);
        }
        Login data = userService.login(login);
        if (null == data) {
            return errorMsg(UserConstant.ACCOUNT_EXCEPTION,entity);
        }
        String token = JWTUtils.jwtUtils.getJwtToken(data.getId().toString());
        return EntityUtils.buildResData(entity, SystemConstant.OK, null, token);
    }
}
